package com.fengfeng.sms.provider;

import java.util.ArrayList;
import java.util.List;

import com.fengfeng.sms.dao.Contactdao;
import com.fengfeng.sms.domin.Contact;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;

public class ContactProvider implements Contactdao {
	public List<Contact> getUserInfo(Context context) {
		List<Contact> list = new ArrayList<Contact>();
		Cursor cursor = null;
		try {
			cursor = context.getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI, null, null, null,
					null);
			while (cursor.moveToNext()) {
				String id = cursor.getString(cursor
						.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cursor
						.getString(cursor
								.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				int isHas = Integer
						.parseInt(cursor.getString(cursor
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
				String number = null;
				if (isHas > 0) {
					Cursor c = null;
					try {
						c = context
								.getContentResolver()
								.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
										null,
										ContactsContract.CommonDataKinds.Phone.CONTACT_ID
												+ " = " + id, null, null);
						while (c.moveToNext()) {
							number = c
									.getString(c
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (c != null) {
							c.close();
							c = null;
						}
					}
				}
				Contact contact = new Contact(id, name, number);
				list.add(contact);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}
		return list;
	}
}
